﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.RowIO;
using EffiProz.Core.Errors;
using EffiProz.Core.Indexes;
using EffiProz.Core.Navigators;

namespace EffiProz.Core.Persist
{
    public class RowStoreAVLHybrid : RowStoreAVL, PersistentStore
    {
        TableBase table;
        Session session;
        DataFileCacheSession cache;
        private int maxMemoryRowCount;
        private int memoryRowCount;
        private bool useCache;
        private bool isCached;
        private bool isTempTable;
        private IntKeyHashMapConcurrent rowIdMap;
        int rowIdSequence = 0;

        public RowStoreAVLHybrid(Session session,
                                 PersistentStoreCollection manager,
                                 TableBase table, bool useCache)
        {

            this.session = session;
            this.manager = manager;
            this.table = table;
            this.maxMemoryRowCount = session.getResultMemoryRowCount();
            this.isTempTable = table.getTableType() == TableBase.TEMP_TABLE;
            this.useCache = useCache;

            if (isTempTable)
            {
                this.rowIdMap = new IntKeyHashMapConcurrent();
            }

            if (table.getTableType() == TableBase.RESULT_TABLE)
            {
                timestamp = session.getActionTimestamp();
            }

            // temp code to force use of cache
            /*
                    if (useCache) {
                        cache = session.sessionData.getResultCache();

                        if (cache != null) {
                            isCached = useCache;

                            cache.storeCount++;
                        }
                    }
            */

            //
            resetAccessorKeys(table.getIndexList());
            manager.setStore(table, this);
        }

        public override bool isMemory()
        {
            return !isCached;
        }

        public override int getAccessCount()
        {
            return isCached ? cache.getAccessCount()
                            : 0;
        }

        public override void set(CachedObject obj) { }

        public override CachedObject get(int i)
        {

            try
            {
                if (isCached)
                {
                    return cache.get(i, this, false);
                }
                else
                {
                    return (CachedObject)rowIdMap.get(i);
                }
            }
            catch (CoreException )
            {
                return null;
            }
        }

        public CachedObject getKeep(int i)
        {

            try
            {
                if (isCached)
                {
                    return cache.get(i, this, true);
                }
                else
                {
                    return (CachedObject)rowIdMap.get(i);
                }
            }
            catch (CoreException )
            {
                return null;
            }
        }

        public override CachedObject get(int i, bool keep)
        {

            try
            {
                if (isCached)
                {
                    return cache.get(i, this, keep);
                }
                else
                {
                    return (CachedObject)rowIdMap.get(i);
                }
            }
            catch (CoreException )
            {
                return null;
            }
        }

        public override CachedObject get(CachedObject obj, bool keep) {

        try {
            if (isCached) {
                return cache.get(obj, this, keep);
            } else {
                return obj;
            }
        } catch (CoreException ) {
            return null;
        }
    }

        public override int getStorageSize(int i)
        {

            try
            {
                if (isCached)
                {
                    return cache.get(i, this, false).getStorageSize();
                }
                else
                {
                    return 0;
                }
            }
            catch (CoreException )
            {
                return 0;
            }
        }

        public override void add(CachedObject obj) {

        if (isCached) {
            int size = obj.getRealSize(cache.rowOut);

            size = cache.rowOut.getStorageSize(size);

            obj.setStorageSize(size);
            cache.add(obj);
        }
    }

        public override CachedObject get(RowInputInterface _in)
        {

            try
            {
                if (isCached)
                {
                    return new RowAVLDisk(table, _in);
                }
            }
            catch (CoreException )
            {
                return null;
            }
            catch (System.IO.IOException )
            {
                return null;
            }

            return null;
        }

        public override CachedObject getNewCachedObject(Session session, Object obj)
        {

            if (isCached)
            {
                Row row = new RowAVLDisk(table, (Object[])obj);

                add(row);

                if (isTempTable)
                {
                    RowAction.addAction(session, RowAction.ACTION_INSERT,
                                        (Table)table, row);
                }

                return row;
            }
            else
            {
                memoryRowCount++;

                if (useCache && memoryRowCount > maxMemoryRowCount)
                {
                    changeToDiskTable();

                    return getNewCachedObject(session, obj);
                }

                Row row = new RowAVL(table, (Object[])obj);
                int id = rowIdSequence++;

                row.setPos(id);

                if (rowIdMap != null)
                {
                    rowIdMap.put(id, row);
                }

                if (isTempTable)
                {
                    RowAction.addAction(session, RowAction.ACTION_INSERT,
                                        (Table)table, row);
                }

                return row;
            }
        }

        public override void removeAll()
        {

            if (!isCached)
            {
                if (rowIdMap != null)
                {
                    rowIdMap.clear();
                }
            }

            ArrayUtil.fillArray(accessorList, null);
        }

        public override void remove(int i)
        {

            if (isCached)
            {
                cache.remove(i, this);
            }
            else
            {
                if (rowIdMap != null)
                {
                    rowIdMap.remove(i);
                }
            }
        }

        public override void removePersistence(int i) { }

        public override void release(int i)
        {

            if (isCached)
            {
                cache.release(i);
            }
        }

        public override void commitPersistence(CachedObject row) { }

        public override DataFileCache getCache()
        {
            return cache;
        }

        public override void setCache(DataFileCache cache)
        {
            throw Error.runtimeError(ErrorCode.U_S0500, "RowStoreAVLHybrid");
        }

        public override void release()
        {

            ArrayUtil.fillArray(accessorList, null);

            if (isCached)
            {
                cache.storeCount--;

                if (cache.storeCount == 0)
                {
                    cache.clear();
                }

                cache = null;
                isCached = false;
            }
            else
            {
                if (rowIdMap != null)
                {
                    rowIdMap.clear();
                }
            }

            manager.setStore(table, null);
        }

        public override void setAccessor(Index key, CachedObject accessor)
        {

            Index index = (Index)key;

            accessorList[index.getPosition()] = accessor;
        }

        public override void setAccessor(Index key, int accessor) { }

        public override void resetAccessorKeys(Index[] keys)
        {

            if (indexList.Length == 0 || indexList[0] == null
                    || accessorList[0] == null)
            {
                indexList = keys;
                accessorList = new CachedObject[indexList.Length];

                return;
            }

            throw Error.runtimeError(ErrorCode.U_S0500, "RowStoreAVLHybrid");
        }

        public void changeToDiskTable()
        {

            cache = session.sessionData.getResultCache();

            if (cache != null)
            {
                RowIterator iterator = table.rowIterator(this);

                ArrayUtil.fillArray(accessorList, null);

                isCached = true;

                cache.storeCount++;

                while (iterator.hasNext())
                {
                    Row row = iterator.getNextRow();
                    Row newRow = (Row)getNewCachedObject(session, row.getData());

                    indexRow(null, newRow);
                }

                if (rowIdMap != null)
                {
                    rowIdMap.clear();
                }
            }

            maxMemoryRowCount = int.MaxValue;
        }

        public override CachedObject getNewInstance(int size)
        {
            return null;
        }
    }
}
